<?php

namespace app\admin\controller;

use \think\Db;
use \think\Reuquest;

class auth extends Main
{
    function index()
    {
        //获取菜单列表
        $auth = Db::name('auth_rule')
            ->order(['sort' => 'ASC'])
            ->select();
        $auth = array2Level($auth);
        return $this->fetch('index', ['auth' => $auth]);
    }

    /**
     * 新增菜单
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $str = $post['icon'];
            $post['icon'] = checkStr($str);
//            $validate = validate('auth');
//            $res = $validate->check($post);
//            if ($res !== true) {
//                $this->error($validate->getError());
//            } else {
            Db::name('auth_rule')
                ->insert($post);
            $this->success('新增成功');
//            }
        } else {
            $auth = Db::name('auth_rule')->order(['sort' => 'asc'])->select();
            $auth = array2Level($auth);
            return $this->fetch('add', ['auth' => $auth]);
        }

    }

    /**
     * 编辑菜单
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    function edit($id)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $id = $post['id'];
//            $validate = validate('auth');
//            $validate->scene('edit');
//            $res = $validate->check($post);
//            if ($res !== true) {
//                $this->error($validate->getError());
//            } else {
            unset($post['id']);
            Db::name('auth_rule')
                ->where('id', $id)
                ->update($post);
            $this->success('编辑成功');
//            }
        } else {
            //菜单列表
            $auth = Db::name('auth_rule')->order(['sort' => 'asc'])->select();
            $auth = array2Level($auth);
            $this->assign('auth', $auth);
            //当前菜单数据
            $data = Db::name('auth_rule')
                ->where('id', $id)
                ->find();
            return $this->fetch('edit', ['data' => $data]);
        }

    }

    /**
     * 菜单删除
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    function delete()
    {
        $id = $this->request->post('id');
        $juge = Db::name('auth_rule')
            ->where('pid', $id)
            ->find();
        if (!empty($juge)) {
            $this->error('请先删除子菜单');
        } else {
            Db::name('auth_rule')
                ->delete($id);
            $this->success('删除成功');
        }
    }

    /******************************** 角色管理 *****************************************/
    /**
     * 角色页面展示
     * @return mixed
     * @throws \think\exception\DbException
     */
    function role()
    {
        $uid = isession('user_id');
        $where['flag'] = 1;
        $where['creater_id'] = $uid;
        if ($uid == 1) {//超级管理员
            $where['company_id'] = isession('company_id');
            //获取公司列表
            $this->assign('company', arrayCombine($this->getDictionary('company'), 'id'));
        }
        $search = sget('title');
        $search && $where['title'] = ['like', '%' . $search . '%'];
        $role = Db::name('auth_group')
            ->where($where)
            ->order('sort asc,id asc')
            ->paginate(15, false, ['query' =>
                [
                    'title' => $search
                ]]);
        $this->assign('type', isession('type'));
        $this->assign('user_id', $uid);
        $this->assign('role', $role);
        return $this->fetch('role');
    }

    /**
     * 新增角色
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function addRole()
    {
        if (post()) {
            $data = post();
            $user_id = isession('user_id');
            $company_id = isession('company_id');
            $where = array(
                'title' => $data['title'],
                'flag' => 1,
                'company_id' => $company_id
            );
            $res = Db::name('auth_group')->where($where)->find();
            if (checkArr($res)) {
                $this->error('该角色已存在');
            }

            $concierge = 2;
            $level = isession('super');
            if (isset($data['type'])) {
                $data['type'] == 1 && $level = $level + 1;
                if (isession('type') != $data['type']) {
                    $concierge = 1;
                }
            }
            $insertData = array(
                'title' => $data['title'],
                'status' => $data['status'],
                'type' => isset($data['type']) ? $data['type'] : 2,
                'sort' => $data['sort'],
                'flag' => 1,
                'creater_id' => $user_id,
                'level' => $level,
                'company_id' => $company_id,
                'concierge' => $concierge
            );

            Db::name('auth_group')->insert($insertData);
            $this->success('添加成功');
        } else {
            $this->assign('type', isession('type'));
            return $this->fetch('roleAdd');
        }
    }

    /**
     * 角色编辑
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    function editRole($id)
    {
        if (post()) {
            $data = post();
            if ($data['id'] == 1) {
                $this->error('超级管理员状态无法编辑');
            }

            $company_id = isession('company_id');
            $where = array(
                'title' => $data['title'],
                'flag' => 1,
                'company_id' => $company_id
            );

            $res = Db::name('auth_group')
                ->where($where)
                ->find();
            if (checkArr($res) && ($res['id'] != $data['id'])) {
                $this->error('该角色已存在');
            }

            $updateDate = array(
                'title' => $data['title'],
                'status' => $data['status'],
                'sort' => $data['sort']
            );
            $res = Db::name('auth_group')
                ->where('id', $data['id'])
                ->update($updateDate);
            if ($res) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败，请重试');
            }
        } else {
            $data = Db::name('auth_group')
                ->where('id', $id)
                ->find();
            return $this->fetch('roleEdit', ['data' => $data]);
        }
    }

    /**
     * 删除角色 逻辑删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function delRole()
    {
        $id = $this->request->post('id');
        if ($id !== '1') {
            $where = array('id' => $id, 'creater_id' => $this->request->session('user_id'));
            $res = Db::name('auth_group')
                ->where($where)
                ->update(['flag' => 2]);
            if ($res) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('超级管理员无法删除');
        }
    }

    /**
     * 角色复制
     */
    public function copyRole()
    {
        if (post()) {
            $data = post();
            $user_id = isession('user_id');
            $company_id = isession('company_id');
            $where = array(
                'title' => $data['title'],
                'flag' => 1,
                'company_id' => $company_id
            );
            $res = Db::name('auth_group')->where($where)->find();
            if (checkArr($res)) {
                $this->error('该角色已存在');
            }

            $concierge = 2;
            $level = isession('super');
            if (isset($data['type'])) {
                $data['type'] == 1 && $level = $level + 1;
                if (isession('type') != $data['type']) {
                    $concierge = 1;
                }
            }
            $insertData = array(
                'title' => $data['title'],
                'status' => 1,
                'type' => isset($data['type']) ? $data['type'] : 2,
                'sort' => $data['sort'],
                'flag' => 1,
                'creater_id' => $user_id,
                'level' => $level,
                'company_id' => $company_id,
                'concierge' => $concierge
            );

            Db::name('auth_group')->insert($insertData);
            $role_id = Db::name('auth_group')->getLastInsID();
            $sql = "insert into  ean_auth_role_power (rule_id,role_id) select rule_id," . $role_id . " from ean_auth_role_power where role_id=" . $data['id'];
            Db::execute($sql);
            $this->success('添加成功');
        } else {
            $this->assign('type', isession('type'));
            return $this->fetch('copyRole');
        }
    }

    /******************************* 分配权限  *******************************************/
    /**
     * 获取权限菜单
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getJson()
    {
        $id = $this->request->post('id');
        if ($id == 1) {
            $this->error('超级管理员无需授权');
        }
        $session = $this->request->session();
        //获取当前用户权限菜单信息
        if ($session['role_id'] == 1) {
            //超级管理员获取全部菜单列表
            $where['flag'] = 1;
        } else {
            $auth_rule = Db::name('auth_role_power')
                ->where('role_id', $session['role_id'])
                ->select();
            $rule_ids = join(',', array_column($auth_rule, 'rule_id'));
            $where = "flag=1 AND id in (" . $rule_ids . ") ";
        }

        $auth_rule_list = Db::name('auth_rule')
            ->where($where)
            ->field('id,pid,title')
            ->select();
        if (!$id) {
            return $auth_rule_list;
        }
        //选中角色已有的权限菜单
        $auth_group_data = Db::name('auth_role_power')
            ->where('role_id', $id)
            ->select();
        $auth_rules = array_column($auth_group_data, 'rule_id');

        foreach ($auth_rule_list as $key => $value) {
            in_array($value['id'], $auth_rules) && $auth_rule_list[$key]['checked'] = true;
        }
        return $auth_rule_list;
    }

    /**
     * 更新权限组规则
     * @param $id
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function updateAuthGroupRule($id)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if ($post['id'] == 1) {
                if (session('user_id') !== 1) $this->error('超级管理员信息无法编辑');
            }
            //先删除原有角色菜单权限信息
            Db::name('auth_role_power')
                ->where('role_id', $post['id'])
                ->delete();

            if (checkArr($post['auth_rule_ids'])) {
                foreach ($post['auth_rule_ids'] as $key => $value) {
                    $data[$key]['rule_id'] = $value;
                    $data[$key]['role_id'] = $post['id'];
                }
                Db::name('auth_role_power')->insertAll($data);
                $this->success('授权成功');
            } else {
                $this->success('授权成功');
            }
        } else {
            $this->assign('id', $id);
            return $this->fetch('auth');
        }
    }

    /**
     * 批量授权
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function batchLicensing()
    {
        if (post()) {
            $data = post();
            if (checkArr($data['id'])) {
                $where['role_id'] = ['in', $data['id']];
            } else {
                $where['role_id'] = $data['id'];
            }
            //先删除原有角色菜单权限信息
            Db::name('auth_role_power')
                ->where($where)
                ->delete();

            if (checkArr($data['auth_rule_ids'])) {
                foreach ($data['id'] as $value) {
                    foreach ($data['auth_rule_ids'] as $v) {
                        $insertData[] = array(
                            'rule_id' => $v,
                            'role_id' => $value
                        );
                    }
                }
                Db::name('auth_role_power')->insertAll($insertData);
                $this->success('授权成功');
            } else {
                $this->success('授权成功');
            }
        } else {
            $uid = isession('user_id');
            $where['flag'] = 1;
            $where['status'] = 1;
            $where['creater_id'] = $uid;
            if ($uid == 1) {//超级管理员
                $where['company_id'] = isession('company_id');
            }

            $role = Db::name('auth_group')
                ->field('id,title')
                ->where($where)
                ->order('sort asc,id asc')
                ->select();
            $this->assign('role', $role);
            return $this->fetch('batchAuth');
        }
    }
}
